using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Yoozoo.UI.YGUI;

namespace com.yoozoo.gta.Art.BeautyGirl
{
    public class ChangeHairTool : MonoBehaviour
    {
        [Header("发型更换按钮父节点")][SerializeField] public RectTransform rectTransform; // 皮肤更换菜单的父节点
        [Header("发型更换按钮预制体")][SerializeField] public GameObject hairMenuOptions; // 皮肤更换菜单的选项预制体
        [Header("所有发型列表")]public GameObject[] hairList; // 当前角色所拥有的所有发型列表
        public int currIdx = 0; // 当前发型的索引
        [SerializeField] private List<YButton> buttons = new List<YButton>(); // 皮肤更换菜单的按钮列表
        void Start()
        {
            if (rectTransform == null || hairMenuOptions == null || hairList.Length == 0)
            {
                Debug.LogError("ChangeMaterialTool: ChangeMaterial() skinnedMeshRenderer or hairMaterials is null or empty");
                return;
            }
            
            int hairsCount = hairList.Length;
            int hairGroups = hairsCount / 2;
            //取余
            int hairMaterialRemainder = hairsCount % 2;
            
            for (int i = 0; i < hairGroups; i++)
            {
                GameObject instHairGroup = Instantiate(hairMenuOptions, rectTransform);
                buttons.AddRange(instHairGroup.GetComponentsInChildren<YButton>());
            }
            if(hairMaterialRemainder > 0)
            {
                GameObject instHairGroup = Instantiate(hairMenuOptions, rectTransform);
                buttons.Add(instHairGroup.GetComponentsInChildren<YButton>()[0]);
                Destroy(instHairGroup.GetComponentsInChildren<YButton>()[1].transform.parent.gameObject);
            }
            
            for (int i = 0; i < buttons.Count; i++)
            {
                int index = i;
                buttons[i].onClick.AddListener(() => OnButtonClicked(index));
                buttons[i].GetComponentInChildren<Text>().text = "发型 " + i;
                buttons[i].GetComponentInChildren<Text>().name = "发型 " + i;
            }
        }

        private void OnButtonClicked(int index)
        {
            Debug.Log("ChangeHairTool: OnButtonClicked() index: " + index);
            for (int i = 0; i < hairList.Length; i++)
            {
                hairList[i].SetActive(i == index);
            }
            currIdx = index;
        }
    }
}
